package xin.shaozeming.base.common.servlet.interceptor;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import xin.shaozeming.base.common.Enum.base.State;
import xin.shaozeming.base.common.Response;
import xin.shaozeming.base.common.aop.annotation.ParamsDecrypted;
import xin.shaozeming.base.common.aop.annotation.SysLogger;
import xin.shaozeming.base.common.aop.annotation.TokenCheck;
import xin.shaozeming.base.common.servlet.ParameterRequestWrapper;
import xin.shaozeming.base.common.utils.ApplicationContextHolder;
import xin.shaozeming.base.common.utils.DateUtils;
import xin.shaozeming.base.common.utils.TokenUtils;
import xin.shaozeming.base.po.UserPO;
import xin.shaozeming.base.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @author: 邵泽铭
 * @date: 2019/10/16
 * @description:
 **/

@Log4j2
public class TokenInterceptor extends HandlerInterceptorAdapter {

    private UserService userService;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(userService==null){
            userService=ApplicationContextHolder.getApplicationContext().getBean(UserService.class);
        }

        if (handler instanceof HandlerMethod &&((HandlerMethod) handler).getMethod().getAnnotation(TokenCheck.class) != null) {
            String token=TokenUtils.getToken(request);
            if(StringUtils.isEmpty(token)){
                InterceptorConfig.returnResponse(response,new Response<>(State.RES_NOLOGIN.getCode()));
                return false;
            }
            /*查看会话token是否失效*/
            UserPO userPO= userService.checkToken(token);
            if(userPO==null){
                InterceptorConfig.returnResponse(response,new Response<>(State.RES_NOLOGIN.getCode()));
                return false;
            }
            /*延长token失效时间*/
            userPO.setTokenExpire(DateUtils.addDate(new Date(), 3));
            if(!userService.updateById(userPO)){
                InterceptorConfig.returnResponse(response,new Response<>(State.RES_NOLOGIN.getCode()));
                return false;
            }

            if(((HandlerMethod) handler).getMethod().getAnnotation(SysLogger.class) != null){
                if(request instanceof ParameterRequestWrapper){
                    request.getParameterMap().put("x_username", new String[]{userPO.getUsername()});
                }
            }
        }

        return super.preHandle(request, response, handler);
    }


}
